package com.ddogring.web.controller.business;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ddogring.business.domain.User;
import com.ddogring.business.service.IUserService;
import com.ddogring.common.annotation.RepeatSubmit;
import com.ddogring.common.constant.Constants;
import com.ddogring.common.constant.HttpStatus;
import com.ddogring.common.constant.UserConstants;
import com.ddogring.common.core.controller.BaseController;
import com.ddogring.common.core.domain.AjaxResult;
import com.ddogring.common.core.domain.entity.SysUser;
import com.ddogring.common.core.domain.model.LoginBody;
import com.ddogring.common.core.domain.model.LoginUser;
import com.ddogring.common.utils.SecurityUtils;
import com.ddogring.common.utils.StringUtils;
import com.ddogring.framework.web.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.regex.Pattern;

/**
 * @BelongsProject: eshop
 * @BelongsPackage: com.ddogring.web.controller.business
 * @Author: DdogRing
 * @CreateTime: 2023-01-31  09:07
 * @Description: TODO
 * @Version: 1.0
 */
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {

    @Autowired
    private IUserService userService;

    @Autowired
    private TokenService tokenService;

    /**
     * 新增用户
     */
    @PostMapping("/register")
    @RepeatSubmit(message = "请勿重复注册")
    public AjaxResult register(@Valid @RequestBody User user)
    {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUsername())))
        {
            return AjaxResult.error("新增用户'" + user.getUsername() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhone())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return AjaxResult.error("新增用户'" + user.getUsername() + "'失败，手机号码已存在");
        }

        // 原密码
        String password = user.getPassword();
        // 密码加密
        user.setPassword(SecurityUtils.encryptPassword(password));
        boolean save = userService.save(user);

        if (save) {
            LoginBody loginBody = new LoginBody();
            loginBody.setUsername(user.getUsername());
            loginBody.setPassword(password);
            AjaxResult login = login(loginBody);
            return HttpStatus.SUCCESS == (int)login.get("code") ? login : AjaxResult.error("注册失败，请联系系统管理员");
        }
        return AjaxResult.error("注册失败，请联系系统管理员");
    }

    /**
     * @description: 登录
     * @author: DdogRing
     * @date: 2023/1/31 11:03
     * @param: [loginBody]
     * @return: com.ddogring.common.core.domain.AjaxResult
     **/
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = null;
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isEmpty(loginBody.getUsername())) {
            return AjaxResult.error("用户名不能为空");
        } else if (StringUtils.isEmpty(loginBody.getPassword())) {
            return AjaxResult.error("密码不能为空");
        }
        queryWrapper.eq("username", loginBody.getUsername());
        User userDB = userService.getOne(queryWrapper);

        // 生成令牌
        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(userDB.getId().longValue());
        SysUser sysUser = new SysUser();
        sysUser.setUserName(userDB.getUsername());
        sysUser.setPhonenumber(userDB.getPhone());
        sysUser.setNickName(userDB.getNickname());
        loginUser.setUser(sysUser);
        if (SecurityUtils.matchesPassword(loginBody.getPassword(), userDB.getPassword())) {
            // 生成token
            String token = tokenService.createToken(loginUser);
            ajax = AjaxResult.success();
            ajax.put(Constants.TOKEN, token);
            ajax.put("userInfo", userDB);
            return ajax;
        } else {
            return AjaxResult.error("用户名或密码错误");
        }
    }

    /**
     * @description: 获取当前用户信息
     * @author: DdogRing
     * @date: 2023/2/3 17:47
     * @param: []
     * @return: com.ddogring.common.core.domain.AjaxResult
     **/
    @GetMapping("/getUserInfo")
    public AjaxResult getUserInfo() {
        LoginUser loginUser = getLoginUser();
        return AjaxResult.success(userService.getById(loginUser.getUserId()));
    }

    /**
     * @description: 绑定邮箱
     * @author: DdogRing
     * @date: 2023/1/31 09:58
     * @param: [user]
     * @return: com.ddogring.common.core.domain.AjaxResult
     **/
    @PostMapping("/bind")
    public AjaxResult bind(@RequestBody User user) {

        if (StringUtils.isEmpty(user.getUsername())) {
            return AjaxResult.error("用户名不存在");
        }

        if (StringUtils.isEmpty(user.getEmail())) {
            return AjaxResult.error("邮箱地址不能为空");
        }

        if (user.getPhone() != null) {
            if (!Pattern.matches("^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\\d{8}$", user.getPhone())) {
                return AjaxResult.error("手机号格式错误");
            }
        }
        return toAjax(userService.bind(user));
    }

    /**
     * 重置密码
     */
    @PostMapping("/updatePwd")
    public AjaxResult updatePwd(@RequestParam("oldPassword") String oldPassword, @RequestParam("newPassword") String newPassword)
    {
        LoginUser loginUser = getLoginUser();
        String userName = loginUser.getUsername();

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userName);
        User userDB = userService.getOne(queryWrapper);

        if (!SecurityUtils.matchesPassword(oldPassword, userDB.getPassword()))
        {
            return AjaxResult.error("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, userDB.getPassword()))
        {
            return AjaxResult.error("新密码不能与旧密码相同");
        }
        if (!newPassword.matches("(?![0-9A-Z]+$)(?![0-9a-z]+$)(?![a-zA-Z]+$)[0-9A-Za-z~!@#$%^&*()_\\-+=<>?:{}|,.\\/;'\\[\\]·~！@#￥%……&*（）——\\-+={}|《》？：“”【】、；‘'，。、]{6,18}$")) {
            return AjaxResult.error("密码必须包含数字、大小写字母，且至少六位");
        }

        UpdateWrapper<User> wrapper = new UpdateWrapper<>();
        wrapper.set("password", SecurityUtils.encryptPassword(newPassword));
        wrapper.eq("username", userName);
        if (userService.update(wrapper))
        {
            // 更新缓存用户密码
            loginUser.getUser().setPassword(SecurityUtils.encryptPassword(newPassword));
            tokenService.setLoginUser(loginUser);
            return AjaxResult.success();
        }
        return AjaxResult.error("修改密码异常，请联系管理员");
    }

}

